import React, {Component} from 'react'
import {Button, message, Spin, Table} from "antd"
import {RootState} from '../../reducers'
import {connect, ConnectedProps} from 'react-redux'
import ButtonGroup from 'antd/lib/button/button-group'
import DeleteArticleModal from './DeleteArticleModal'
import {RouteComponentProps, withRouter} from 'react-router-dom'
import ArticleInfo from "../../types/ArticleInfo";
import {listArticleInfoReq, listArticleOnID, queryArticleAmount, queryArticleAmountOnID} from "../../requests/article";
import moment from 'moment'
import ArticleType from '../../types/ArticleType'
import {getRes} from "../../configFile";
import UserType from "../../types/UserType";


interface PropsFromRedux extends ConnectedProps<typeof connector>, RouteComponentProps {
    articleType: string
}

interface IState {
    ArticleSource: Array<ArticleInfo & { key: number }>       //显示信息
    amount: number                                                          //总共条目
    offset: number                                                          //偏移量
    limit: number                                                           //条数
    isLoading: boolean                                                       //是否加载中
    modifyModalVisible: boolean,                                             //编辑的模态框是否为显示状态
}

class ModifyArticleList extends Component<PropsFromRedux, IState> {

    constructor(props: PropsFromRedux) {
        super(props)
        this.state = {
            ArticleSource: [],
            amount: 0,
            offset: 0,
            limit: 10,
            isLoading: true,
            modifyModalVisible: false
        }
    }


    //删除文章
    deleteArticle = (articleID: number, title: string, refresh: () => void) => {
        DeleteArticleModal(articleID, title, refresh)
    }


    //获取文章数据
    getArticle = async () => {
        try {
            this.setState({
                ...this.state,
                isLoading: true
            })
            // const amountRes = await queryArticleAmountOnID(this.props.articleType, this.props.userID)
            const amountRes = this.props.userType === UserType.SUPERVISOR ?
                getRes(await queryArticleAmount(this.props.articleType))
                :
                getRes(await queryArticleAmountOnID(this.props.articleType, this.props.userID));
            const res = this.props.userType === UserType.SUPERVISOR ?
                getRes(await listArticleInfoReq(this.props.articleType, this.state.offset, this.state.limit))
                :
                getRes(await listArticleOnID(this.props.articleType, this.state.offset, this.state.limit, this.props.userID))


            this.setState({
                ArticleSource: res.data.map((item: ArticleInfo) => Object.assign({}, item, {key: item.articleID})),
                amount: amountRes.data
            })
        } catch (error) {
            message.error(error.toString())
        } finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    componentDidMount() {
        this.getArticle()
    }

    columns = [{
        title: '文章标题',
        dataIndex: 'title',
        key: 'title',
    },
        {
            title: '文章创建时间',
            dataIndex: 'creationTimestamp',
            key: 'creationTimestamp',
            render: (record: number) => {
                return moment(record).format('YYYY-MM-DD')
            }
        },
        {
            title: '上次修改时间',
            dataIndex: 'lastModifiedTimestamp',
            key: 'lastModifiedTimestamp',
            render: (record: number) => {
                return moment(record).format('YYYY-MM-DD')
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (record: ArticleInfo) => (
                <ButtonGroup>
                    <Button size='middle' type='primary' onClick={() => {
                        this.props.history.push((this.props.userType === UserType.SUPERVISOR ?
                            `/siteManage`
                            :
                            `/personal`) +
                            `/modify${this.props.articleType === ArticleType.EVALUATION ?
                                'ReviewArticle'
                                :
                                'DeviceKnowledge'}/${record.articleID}`)
                    }}
                    >
                        编辑
                    </Button>
                    <Button size='middle' danger
                            onClick={this.deleteArticle.bind(this, record.articleID, record.title, this.getArticle)}
                    >
                        删除
                    </Button>
                </ButtonGroup>
            )
        }]

    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Table columns={this.columns}
                           dataSource={this.state.ArticleSource}
                           pagination={{
                               onChange: (page, pageSize) => {
                                   console.log(page, pageSize);
                                   if (!!pageSize) {
                                       this.setState({
                                           offset: (page - 1) * (pageSize),
                                           limit: (pageSize)
                                       },()=>{
                                           this.getArticle()
                                       })
                                   } else {
                                       console.error('pageSize == undefined')
                                   }
                               },
                               defaultPageSize: this.state.limit,
                               total: this.state.amount,
                               showSizeChanger: false
                           }}/>
                </Spin>

            </div>
        )
    }
}

//connect加入props
const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID,
        userType: state.loginReducers.userType
    }
}

const connector = connect(mapStateToProps)
export default withRouter(connector(ModifyArticleList))